//index.js
//获取应用实例
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');

Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail:{},
    swiperCurrent: 0,  
    hasMoreSelect:false,
    //selectSize:"选择：",
    selectSize:"选择： 请选择规格",
    selectSizePrice:0,
    totalScoreToPay: 0,
    shopNum:0,
    hideShopPopup:true,
    buyNumber:0,
    buyNumMin:1,
    buyNumMax:0,
    reputationStr:['好评', '中评', '差评'],
    propertyChildIds:"",
    propertyChildNames:"",
    canSubmit:false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo:{},
    pin_tuan_tpl:null,
    shopType: "addShopCar",//购物类型，加入购物车或立即购买，默认为加入购物车
  },

  //事件处理函数
  swiperchange: function(e) {
      //console.log(e.detail.current)
       this.setData({  
        swiperCurrent: e.detail.current  
    })  
  },
  onLoad: function (e) {
    if (e.inviter_id) {
      wx.setStorage({
        key: 'inviter_id_' + e.id,
        data: e.inviter_id
      })
    }
    var that = this;
    that.data.kjId = e.kjId;
    // 获取购物车数据
    wx.getStorage({
      key: 'shopCarInfo',
      success: function(res) {
        that.setData({
          shopCarInfo:res.data,
          shopNum:res.data.shopNum
        });
      } 
    })
    wx.request({
      url: app.globalData.domain + '/item/'+ e.id + '/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      
      success: function(res) {
        //console.log(res.data,"goodsDetail")
        if (res.data) {
          that.setData({
            hasMoreSelect: true,
            haspingtuan: false,
            selectSize: that.data.selectSize,
            selectSizePrice: res.data.price,
            // totalScoreToPay: res.data.data.basicInfo.minScore
          });
          // if (res.data.bulk_purchase_tpl_set!=null) {

          //   that.setData({
          //     haspingtuan: true,
          //     pingtuanList: res.data.wx_app_bulk_purchase_set,
          //     plan_time: res.data.bulk_purchase_tpl_set.plan_end_time,
          //     pin_tuan_tpl: res.data.bulk_purchase_tpl_set.pk
          //   });
            
          // }
        }
        // if (res.data.data.properties) {
        //   for (var i = 0; i < res.data.data.properties.length; i++) {
        //     selectSizeTemp = selectSizeTemp + " " + res.data.data.properties[i].name;
        //   }
        //   that.setData({
        //     hasMoreSelect: true,
        //     selectSize: that.data.selectSize + selectSizeTemp,
        //     selectSizePrice: res.data.data.basicInfo.minPrice,
        //     totalScoreToPay: res.data.data.basicInfo.minScore
        //   });
        // }
        // if (res.data.pintuan) {
        //   that.pingtuanList(e.id)
        // }
        that.data.goodsDetail = res.data;
        // if (res.data.data.basicInfo.videoId) {
        //   that.getVideoSrc(res.data.data.basicInfo.videoId);
        // }
        that.setData({
          goodsDetail: res.data,
          //selectSizePrice: res.data.price,
          // totalScoreToPay: res.data.data.basicInfo.minScore,
          // buyNumMax: res.data.data.basicInfo.stores,
          // buyNumber: (res.data.data.basicInfo.stores > 0) ? 1 : 0
        });
        WxParse.wxParse('article', 'html', res.data.detail, that, 5);
      }
    })
    wx.request({
      url: app.globalData.domain + '/wxapp/bulk_purchase_tpl/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      data: {
        item: e.id
      },
      success: function (res) {
        //console.log(res,"item_wxapp_bulk_purchase_tpl")
        if(res.statusCode==200){
          if(res.data.length>0){
              that.setData({
                haspingtuan: true,
                plan_time: res.data[0].plan_end_time,
                pin_tuan_tpl: res.data[0].pk
             });
          }
        }

      },
    })
      wx.request({
        url: app.globalData.domain + '/wxapp/bulk_purchase/',
        header: {
          'Authorization': 'JWT ' + wx.getStorageSync('token')
        },
        data: {
          is_commander:'True',
          group_active:2,
          item: e.id
        },
        success: function (res) {
          //console.log(res,that.data.haspingtuan,"item_wxapp/bulk_purchase")
          if (res.statusCode == 200 && that.data.haspingtuan) {
            if (res.data != null) {
              that.setData({
                pingtuanList: res.data,
              });
            }
          }

        },
      })
    
    this.reputation(e.id);
    this.getKanjiaInfo(e.id);
  },
  goShopCar: function () {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  toAddShopCar: function () {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  tobuy: function () {
    this.setData({
      shopType: "tobuy",
      //selectSizePrice: this.data.goodsDetail.basicInfo.minPrice
      selectSizePrice: this.data.goodsDetail.price
    });
    this.bindGuiGeTap();
  },  
  toPingtuan: function () {
    this.setData({
      shopType: "toPingtuan",
      //selectSizePrice: this.data.goodsDetail.basicInfo.pingtuanPrice
    });
    this.bindGuiGeTap();
  },  
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
     this.setData({  
        hideShopPopup: false 
    })  
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
     this.setData({  
        hideShopPopup: true 
    })  
  },
  numJianTap: function() {
     if(this.data.buyNumber > this.data.buyNumMin){
        var currentNum = this.data.buyNumber;
        currentNum--; 
        this.setData({  
            buyNumber: currentNum
        })  
     }
  },   
  numJiaTap: function() {
     if(this.data.buyNumber < this.data.buyNumMax){
        var currentNum = this.data.buyNumber;
        currentNum++ ;
        this.setData({  
            buyNumber: currentNum
        })  
     }
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    // var childs = that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods;
    var childs = that.data.goodsDetail.item_sku_set;
    for(var i = 0;i < childs.length;i++){
      // that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods[i].active = false;
      that.data.goodsDetail.item_sku_set[i].active = false;
    }
    // 设置当前选中状态
    // that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods[e.currentTarget.dataset.propertychildindex].active = true;
    that.data.goodsDetail.item_sku_set[e.currentTarget.dataset.propertyindex].active = true;
    // 获取所有的选中规格尺寸数据
    // var needSelectNum = that.data.goodsDetail.properties.length;
    var needSelectNum = 1;
    var curSelectNum = 0;
    var propertyChildIds = "";
    var propertyChildNames = "";
    // for (var i = 0; i < that.data.goodsDetail.properties.length; i++) {
    //   childs = that.data.goodsDetail.properties[i].childsCurGoods;
    //   for (var j = 0; j < childs.length; j++) {
    //     if (childs[j].active) {
    //       curSelectNum++;
    //       propertyChildIds = propertyChildIds + that.data.goodsDetail.properties[i].id + ":" + childs[j].id + ",";
    //       propertyChildNames = propertyChildNames + that.data.goodsDetail.properties[i].name + ":" + childs[j].name + "  ";
    //     }
    //   }
    // }
    if (that.data.goodsDetail.item_sku_set[e.currentTarget.dataset.propertyindex].active){
      curSelectNum++;
      propertyChildIds = that.data.goodsDetail.item_sku_set[e.currentTarget.dataset.propertyindex].pk
      propertyChildNames = that.data.goodsDetail.item_sku_set[e.currentTarget.dataset.propertyindex].name
    }
    var canSubmit = false;
    if (needSelectNum == curSelectNum) {
      canSubmit = true;
    }
    //计算当前价格
    if (canSubmit){
      wx.request({
        url: app.globalData.domain + '/item_sku/' + propertyChildIds + '/',
        header: {
          'Authorization': 'JWT ' + wx.getStorageSync('token')
        },
        success: function(res){
          //console.log(res.data, "canSubmit price", that.data.shopType)
          that.setData({
            ispingtuansku:false,
            selectSizePrice:res.data.price,
            propertyChildIds:propertyChildIds,
            propertyChildNames:propertyChildNames,
            buyNumMax: res.data.quantity,
            buyNumber: (res.data.quantity>0) ? 1: 0
          });
          if (res.data.discount_price){
            if (that.data.shopType == "toPingtuan" || that.data.shopType == "joinPingtuan"){
              that.setData({
                selectSizePrice: res.data.discount_price,
                ispingtuansku:true
              });
            }
          }
        }
      })
    }
    
    this.setData({
      goodsDetail: that.data.goodsDetail,
      canSubmit:canSubmit
    })  
  },
  /**
  * 加入购物车
  */
  addShopCar:function(){
    if (this.data.goodsDetail.item_sku_set && !this.data.canSubmit) {
      if (!this.data.canSubmit){
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })       
      }
      this.bindGuiGeTap();
      return;
    }
    if(this.data.buyNumber < 1){
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel:false
      })
      return;
    }
    //组建购物车
    var shopCarInfo = this.bulidShopCarInfo();

    this.setData({
      shopCarInfo:shopCarInfo,
      shopNum:shopCarInfo.shopNum
    });

    // 写入本地存储
    wx.setStorage({
      key:'shopCarInfo',
      data:shopCarInfo
    })
    this.closePopupTap();
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 2000
    })
    //console.log(shopCarInfo);

    //shopCarInfo = {shopNum:12,shopList:[]}
  },
	/**
	  * 立即购买
	  */
  buyNow: function (e){
    let that = this
    let shoptype = e.currentTarget.dataset.shoptype
    //console.log(shoptype)
    if (this.data.goodsDetail.item_sku_set && !this.data.canSubmit) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      this.bindGuiGeTap();
      wx.showModal({
        title: '提示',
        content: '请先选择规格尺寸哦~',
        showCancel:false
      })
      return;
    }    
    if(this.data.buyNumber < 1){
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel:false
      })
      return;
    }
    //组建立即购买信息
    var buyNowInfo = this.buliduBuyNowInfo(shoptype);
    // 写入本地存储
    wx.setStorage({
      key:"buyNowInfo",
      data:buyNowInfo
    })
    this.closePopupTap();
    if (shoptype == 'toPingtuan') {
      
      wx.navigateTo({
        url: "/pages/to-pay-order/index?orderType=buyNow&pin_tuan_tpl=" + that.data.pin_tuan_tpl + "&pingtuanOpenId=1&is_commander=1"
      }) 
        
    } else if (shoptype == 'joinPingtuan'){
      wx.navigateTo({
        url: "/pages/to-pay-order/index?orderType=buyNow&is_commander=0&pingtuanOpenId=" + that.data.pingtuanopenid + "&pin_tuan_tpl=" + that.data.pin_tuan_tpl
      }) 
    } 
    else {
      wx.navigateTo({
        url: "/pages/to-pay-order/index?orderType=buyNow"
      })  
    }  
  },
  /**
   * 组建购物车信息
   */
  bulidShopCarInfo: function () {
    // 加入购物车
    var shopCarMap = {};
    //shopCarMap.goodsId = this.data.goodsDetail.basicInfo.id;
    //shopCarMap.pic = this.data.goodsDetail.basicInfo.pic;
    //shopCarMap.name = this.data.goodsDetail.basicInfo.name;
    shopCarMap.goodsId = this.data.goodsDetail.pk;
    //shopCarMap.goodsId = this.data.propertyChildIds
    shopCarMap.pic = this.data.goodsDetail.image;
    shopCarMap.name = this.data.goodsDetail.name;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    // shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    // shopCarMap.logistics = this.data.goodsDetail.logistics;
    // shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;
    var shopCarInfo = this.data.shopCarInfo;
    if (!shopCarInfo.shopNum) {
      shopCarInfo.shopNum = 0;
    }
    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];
      if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.buyNumber;
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {
      shopCarInfo.shopList.push(shopCarMap);
    }
    shopCarInfo.kjId = this.data.kjId;
    return shopCarInfo;
  },
	/**
	 * 组建立即购买信息
	 */
  buliduBuyNowInfo: function (shoptype) {
    var shopCarMap = {};
    //shopCarMap.goodsId = this.data.goodsDetail.basicInfo.id;
    //shopCarMap.pic = this.data.goodsDetail.basicInfo.pic;
    //shopCarMap.name = this.data.goodsDetail.basicInfo.name;
    shopCarMap.goodsId = this.data.goodsDetail.pk;
    shopCarMap.pic = this.data.goodsDetail.image;
    shopCarMap.name = this.data.goodsDetail.name;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    // if (shoptype == 'toPingtuan') {
    //   shopCarMap.price = this.data.goodsDetail.price;
    // }
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    //shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    //shopCarMap.logistics = this.data.goodsDetail.logistics;
    //shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }
    /*    var hasSameGoodsIndex = -1;
        for (var i = 0; i < toBuyInfo.shopList.length; i++) {
          var tmpShopCarMap = toBuyInfo.shopList[i];
          if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
            hasSameGoodsIndex = i;
            shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
            break;
          }
        }
        toBuyInfo.shopNum = toBuyInfo.shopNum + this.data.buyNumber;
        if (hasSameGoodsIndex > -1) {
          toBuyInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
        } else {
          toBuyInfo.shopList.push(shopCarMap);
        }*/

    buyNowInfo.shopList.push(shopCarMap);
    buyNowInfo.kjId = this.data.kjId;
    return buyNowInfo;
  },   
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.name,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.pk + '&inviter_id=' + wx.getStorageSync('uid'),
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  reputation: function (goodsId) {
    var that = this;
    wx.request({
      // url: 'https://api.it120.cc/' + app.globalData.subDomain + '/shop/goods/reputation',
      // data: {
      //   goodsId: goodsId
      // },
      url: app.globalData.domain + '/wxapp/judge/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      data:{
        item: goodsId
      },
      success: function (res) {
        //console.log(res);
        if (res.statusCode == 200) {
          that.setData({
            reputation: res.data.results
          });
        }
      }
    })
  },
  // pingtuanList: function (goodsId) {
  //   var that = this;
  //   wx.request({
  //     url: app.globalData.domain + '/wxapp/bulk_purchase/',
  //     data: {
  //       //goodsId: goodsId
  //       item:goodsId
  //     },
  //     success: function (res) {
  //       if (res.statusCode == 200) {          
  //         that.setData({
  //           pingtuanList: res.data
  //         });
  //       }
  //     }
  //   })
  // },
  // getVideoSrc: function (videoId) {
  //   var that = this;
  //   wx.request({
  //     url: 'https://api.it120.cc/' + app.globalData.subDomain + '/media/video/detail',
  //     data: {
  //       videoId: videoId
  //     },
  //     success: function (res) {
  //       if (res.data.code == 0) {
  //         that.setData({
  //           videoMp4Src: res.data.data.fdMp4
  //         });
  //       }
  //     }
  //   })
  // },
  getKanjiaInfo: function (gid) {
    var that = this;
    if (!app.globalData.kanjiaList || app.globalData.kanjiaList.length == 0){
      that.setData({
        curGoodsKanjia: null
      });
      return;
    }
    let curGoodsKanjia = app.globalData.kanjiaList.find(ele => {
      return ele.goodsId == gid
    });
    if (curGoodsKanjia) {
      that.setData({
        curGoodsKanjia: curGoodsKanjia
      });
    } else {
      that.setData({
        curGoodsKanjia: null
      });
    }
  },
  // goKanjia: function () {
  //   var that = this;
  //   if (!that.data.curGoodsKanjia) {
  //     return;
  //   }
  //   wx.request({
  //     url: 'https://api.it120.cc/' + app.globalData.subDomain + '/shop/goods/kanjia/join',
  //     data: {
  //       kjid: that.data.curGoodsKanjia.id,
  //       token: wx.getStorageSync('token')
  //     },
  //     success: function (res) {
  //       if (res.data.code == 0) {
  //         console.log(res.data);
  //         wx.navigateTo({
  //           url: "/pages/kanjia/index?kjId=" + res.data.data.kjId + "&joiner=" + res.data.data.uid + "&id=" + res.data.data.goodsId
  //         })
  //       } else {
  //         wx.showModal({
  //           title: '错误',
  //           content: res.data.msg,
  //           showCancel: false
  //         })
  //       }
  //     }
  //   })
  // },
  joinPingtuan: function (e) {
    //console.log(e,"joinPingtuan__id")
    this.setData({
      shopType: "joinPingtuan",
      pingtuanopenid :e.currentTarget.dataset.pingtuanopenid
    });
    this.bindGuiGeTap();
  }
})
